<template>
  <el-select
    multiple
    v-model="selectNameArr"
    :placeholder="placeholder"
    clearable
    :size="size"
    :style="{ width: width }"
    @focus="autoFocusInput('search_input1')"
    @change="changeSelectBrand"
    @remove-tag="removeTag"
    popper-class="select-multiple"
  >
    <div class="select-box">
      <!-- <el-form :inline="true" class="select-header">
        <el-form-item label="" label-width="0" class="w_full"> -->
          <el-input
            size="small"
            v-model="searchValue"
            placeholder="请输入关键词"
            clearable
            @input="searchCat"
            class="w_full"
          >
            <div slot="append">
              <i class="el-icon-search"></i>
            </div>
          </el-input>
        <!-- </el-form-item> -->
      <!-- </el-form> -->

      <div class="select-content mt-25" v-if="receiverNameOptModel.length">
        <div
          class="select-item"
          v-for="(item, index) in receiverNameOptModel"
          :key="MultipleSelect"
        >
          <div style="margin: 15px 0 8px; font-weight: bold">
            <el-checkbox
              :indeterminate="item.isIndeterminate"
              v-model="item.checked"
              @change.native="selectAllCat(item, MultipleSelect)"
              >{{ item.label }}</el-checkbox
            >
          </div>
          <el-option
            v-for="(subItem, index) in item.children"
            :key="MultipleSelect"
            :label="subItem"
            :value="subItem"
            class="hasdataoption"
          ></el-option>
        </div>
      </div>
      <div class="select-content" v-else>
        <el-option disabled value="暂无数据" label="暂无数据"></el-option>
      </div>
    </div>
  </el-select>
</template>

<script>
export default {
  name: "MultipleSelect",
  props: {
    receiverNameOpt: {
      //接受的数据为[{id:1,name:'张三',name_en:'zhangsan',...},...]格式
      type: Array,
      default: () => [],
    },
    width: {
      //传入宽度值为字符串形式，如'50%'
      type: String,
      default: "100%",
    },
    size: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
  },
  data() {
    return {
      searchValue: "",
      selectNameArr: [],
      receiverNameOptModel: [],
      loading: false,
      inputVisible: false,
    };
  },
  watch: {
    receiverNameOpt: {
      immediate: true,
      handler(val) {
        if (val.length === 0) {
          this.loading = true;
        } else {
          this.loading = false;
        }
        this.receiverNameOptModel = JSON.parse(
          JSON.stringify(this.receiverNameOpt)
        );
      },
    },
    receiverNameOptModel: {
      immediate: true,
      handler(val) {
        if (val.length === 0) {
          this.inputVisible = false;
          this.autoFocusInput("search_input");
        } else {
          this.inputVisible = true;
          this.autoFocusInput("search_input1");
        }
      },
    },
  },
  methods: {
    // input自动聚焦
    autoFocusInput(classname) {
      this.$nextTick(() => {
        let dom = document.getElementsByClassName(classname)[0];
        if (dom)
          setTimeout(() => {
            dom.children[0].focus();
          }, 200);
      });
    },

    // 选择收件人
    changeSelectBrand(val) {
      console.log('val:', val)
      //  let ret = [];
      //  ret = this.receiverNameOptModel.filter((p) => {
      //    return val.includes(p.label);
      //  });
    //   this.$emit("getmultipleReceiver", ret);
      if ((val.length - 1) < this.receiverNameOptModel.length) {
        this.selectNameArr = this.selectNameArr.filter((item) => {
          return item
        })
      }

      this.receiverNameOptModel.forEach(item=>{
        let arr =  val.filter(vitem => item.children.includes(vitem))
        item.checked = arr.length===item.children.length
        item.isIndeterminate = arr.length> 0 && arr.length < item.children.length
      })

      this.dataChange()
    },

    dataChange() {
      this.$emit('change', this.selectNameArr)
    },

    // 全选单个
    selectSingleCat(item) {
      console.log('item:',item)
      let newArr = []
      if (item.checked) { // 全选
        // console.log('item.checked',item.checked)
        this.receiverNameOptModel.map((subItem) => {
          if (subItem.value === item.value) {
            newArr = subItem.children
          }
        })

      } else {// 反选
        this.selectNameArr = this.selectNameArr.filter(arr=>!item.children.includes(arr))

        // let length = item.children.length;
        // let start = item.children[0];
        // let index = this.selectNameArr.indexOf(start)
        // this.selectNameArr.splice(index, length)

        // console.log(start, index, length)
        // console.log('this.selectNameArr',this.selectNameArr)
      }
      // if()
      // let
      return newArr
    },

     // 全选多个
    selectAllCat(item) {
      let singleCatArr = this.selectSingleCat(item);
      // console.log('singleCatArr',singleCatArr)

      let newArr = this.selectNameArr.concat(singleCatArr)
      this.selectNameArr = Array.from(new Set(newArr)) // 数组去重
      // console.log('selectNameArr', this.selectNameArr)
      item.isIndeterminate = false
      this.dataChange()
    },

    // 全选全部
    selectAll() {
      if (this.selectNameArr.length == 0) {
        // 改变checkbox的状态
        this.receiverNameOptModel = this.receiverNameOptModel.map((item) => {
          let newItem = {
            value: item.value,
            label: item.label,
            children: item.children,
            checked: true
          }
          // console.log('newItem',newItem)
          this.selectAllCat(newItem)
          return newItem
        })
      }

    },

    removeTag(val) {
      for (let i = 0; i < this.selectNameArr.length; i++) {
        if (this.selectNameArr[i] === val) this.selectNameArr.splice(index, 1);
      }
    },

    // 清空品类
    clearAll() {
      this.selectNameArr = []
      // 改变checkbox的状态
      this.receiverNameOptModel = this.receiverNameOptModel.map((item) => {
        item.checked = false
        return item
      });
      this.dataChange()
    },

    // 搜索
    searchCat(query) {
      console.log('query:', query)
      let options = JSON.parse(JSON.stringify(this.receiverNameOpt))
      if (query !== "") {
        let name = query.toLowerCase()
        var filterObj = function(item){
          if(item.hasOwnProperty('children')){
            item.children = item.children.filter(child=>{
              console.log('child:', child.toLowerCase().indexOf(name))
              return child.toLowerCase().indexOf(name) > -1
            })
            if(item.children.length){
              return true
            }
          }else{
            return false
          }
        }
        var result = options.filter(item=>{
          return filterObj(item)
        })
        this.receiverNameOptModel = result
      } else {
        this.receiverNameOptModel = options
        // JSON.parse(
        //   JSON.stringify(this.receiverNameOpt)
        // );
      }
    },
  },
};
</script>

<style lang="scss">
.select-multiple {
  .select-box {
    padding: 10px 25px;
    width: 420px;
  }
  .select-header {
    border-bottom: 1px solid #ccc;
  }
  .select-content {
    // height: 300px;
    // overflow: hidden;
    // overflow-y: auto;
  }
  .el-input-group__append{
    padding: 0 15px;
    background-color: #fff
  }
  .el-select-dropdown__item.hasdataoption {
    display: inline-block;
    height: 32px;
    line-height: 32px;
    background-color: rgba(0,0,0,.06);
    padding: 0px 12px!important;
    margin-bottom: 8px;
    margin-right: 8px;
    border-radius: 2px;
    &.selected{
        background-color: #3b74ff!important;
        color: #fff!important;
        font-weight: normal;
    }
    &.selected::after{
        display: none!important;
    }
  }
  .el-select-dropdown__item{
    text-align: center;
  }
}
</style>
